(function() {
	if (!window.ZDS) {
		window.ZDS = {};
	}
	/**
	* @class 属性拷贝函数
	* @constructor 
	* @param {Object} 原始对象
	* @param {Object} 覆盖对象
	* @param {Object} 默认值独享
	* @return 覆盖后的原始对象
	*/
	ZDS.apply = function(o, c, defaults) {
		var args = Array.prototype.slice.call(arguments, 0);
		var arglen = args.length;
		var execludes = null;
		if (arglen == 4 && args[3]) {
			execludes = args[3];
		}
		if (defaults) {
			ZDS.apply(o, defaults);
		}
		if (o && c && typeof c == 'object') {
			for ( var p in c) {
				/* for IE type problem */
				if (execludes) {
					if (execludes.indexOf(p) == -1) {
						o[p] = c[p];
					}
				} else {
					//console.log('p:'+p+" pv:"+c[p]);
					o[p] = c[p];
				}
			}
		}
		return o;
	};
	
	/**
	* @class easyui datagrid表头右键菜单
	* @constructor 
	* @return null
	*/
	function createColumnMenu() {
		var tmenu = $('<div id="tmenu" style="width:100px;"></div>').appendTo(
				'body');
		var fields = $('#center_table').datagrid('getColumnFields');
		for ( var i = 0, fieldsLen = fields.length; i < fieldsLen; i++) {
			$('<div iconCls="icon-ok"/>').html(fields[i]).appendTo(tmenu);
		}
		tmenu.menu({
			onClick : function(item) {
				if (item.iconCls == 'icon-ok') {
					$('#center_table').datagrid('hideColumn', item.text);
					tmenu.menu('setIcon', {
						target : item.target,
						iconCls : 'icon-empty'
					});
				} else {
					$('#center_table').datagrid('showColumn', item.text);
					tmenu.menu('setIcon', {
						target : item.target,
						iconCls : 'icon-ok'
					});
				}
			}
		});
	}
	/**
	* @class 基对象，提供isType函数判断是否为一个类型
	* @constructor 
	* @return
	*/
	var obj = {
		isType : function(aType) {
			var self = this;
			while (self) {
				if (self == aType) {
					return true;
				}
				self = self.Type;
			}
			return false;
		}
	};
	window.ZDS.obj = obj;
	
	/**
	* @class 可覆盖Class函数
	* @constructor 
	* @param {Object} 基对象
	* @param {Object} 继承对象
	* @return 实现继承的Class
	*/
	function Class(baseClass, classDefine) {
		function class_() {
			this.Type = baseClass;
			for ( var member in classDefine) {
				this[member] = classDefine[member];
			}
		}
		class_.prototype = baseClass;
		return new class_();
	}
	window.ZDS.Class = Class;
	
	/**
	* @class 实例化函数
	* @constructor 
	* @param {Object} Class
	* @param {Object} 构造参数
	* @return Class实例
	*/
	function New(aClass, params) {
		function new_() {
			this.Type = aClass;
			if (aClass.init) {
				aClass.init.apply(this, params);
			}
		}
		;
		new_.prototype = aClass;
		return new new_();
	}
	window.ZDS.New = New;
	
	/**
	* @class 作用域传递代理函数
	* @constructor 
	* @param {Object} 调用函数
	* @param {Object} 传递this
	* @return 传递后的函数
	*/
	var proxy = function(func, thisObject) {
		return function() {
			return func.apply(thisObject, arguments);
		};
	};
	
	/**
	* @class Dom构造工厂
	* @constructor 
	* @return 实现继承的Class
	*/
	var DomFactory = {
		defaultsAttributes : {
			'form' : {
				method : 'post',
				action : 'getFile.do',
				id : 'uploadForm',
				target : 'ajaxUpload'
			},
			'text' : {
				'class' : 'form-text easyui-validatebox',
				className : 'form-text easyui-validatebox'
			},
			'select' : {},
			'checkbox' : {
				className : 'form-checkbox'
			},
			'radio' : {},
			'textarea' : {},
			'file' : {
				type:'span',
				id:'spanButtonPlaceHolder',
				className : 'file'
			},
			'button' : {
				type : 'button'
			},
			'submit' : {
				type : 'submit'
			},
			'iframe' : {
				name : 'ajaxUpload',
				'style.display' : 'none',
				width : 0,
				height : 0
			},
			'date' : {
				className : 'easyui-datebox',
				type:'text',
				editable : false
			},
			'datetime' : {
				type:'text',
				className : 'easyui-datetimebox',
				editable : false
			},
			'linkbutton' : {
				type : 'a',
				className : 'easyui-linkbutton'
			},
			'multifile' : {
				type : 'span',
				id:'spanButtonPlaceHolder',
				className : 'multi'
			}
		},
		/**
		* method 构造DOM函数
		* @constructor 
		* @param {Object} 元素类型，提供基本Dom节点和easyuidom节点类型
		* @param {Object} 属性对象
		* @return 创建后的dom元素
		*/
		createDom : function(et, attributes) {
			var elementType = et == 'hidden' || et == 'button' ||et == 'date' || et == 'datetime'
					|| et == 'submit' || et == 'text' || et == 'radio'
					|| et == 'checkbox' || et == 'file' || et == 'multifile' ? 'input'
					: et;
			if (elementType == 'linkbutton') {
				elementType = 'a';
			}
			var dom = document.createElement(elementType);
			ZDS
					.apply(dom, attributes, this.defaultsAttributes[et],
							et == 'select' || et == 'textarea'
									|| et == 'multifile' || et =='date' || et=='datetime' || et=='linkbutton' ? 'type' : null);
			if (et == 'select') {
				if (attributes.url) {
					if (attributes.store && attributes['nullPropertyName']) {
						if (attributes.store.constructor === Array) {
							for ( var i = 0, storeLen = attributes.store.length; i < storeLen; i++) {
								var item = attributes.store[i];
								if (item[attributes['nullPropertyName']]) {
									var op = new Option(
											item[attributes.displayField],
											item[attributes.valueField]);
									dom.options.add(op);
								}
							}
						}
					}
					jQuery
							.getJSON(
									attributes.url,
									proxy(
											function(data) {
												var rootData = data;
												if(attributes.hasOwnProperty('root'))
												{
													rootData = data[attributes['root']];
												}
												for ( var i = 0, storeLen = rootData.length; i < storeLen; i++) {
													var item = rootData[i];
													var op = new Option(
															item[attributes.displayField],
															item[attributes.valueField]);
													this.options.add(op);
												}
											}, dom));
				} else if (attributes.store) {
					if (attributes.store.constructor === Array) {
						for ( var i = 0, storeLen = attributes.store.length; i < storeLen; i++) {
							var item = attributes.store[i];
							var op = new Option(item[attributes.displayField],
									item[attributes.valueField]);
							dom.options.add(op);
						}
					}
				}
			} else if (et == 'radio') {

			} else if (et == 'checkbox') {

			} else if (et == 'file' || et == 'multifile') {
				var attachResDiv = this.createDom('span',{id:'attach_res_list'});
				var attachDom = this.createDom('div',{id:'attach_div'});
				attachDom.appendChild(dom);
				attachDom.appendChild(attachResDiv);
				dom = attachDom;
			} else if (et == 'linkbutton') {
				$(function(){
					$('#' + dom.id).linkbutton(attributes);
				});
				
			} else if (et == 'date') {
			}
			else if(et == 'datetime')
			{
			}
			if (dom['label']) {
				var spanDom = this.createDom('span');
				var labelDom = this.createDom('label', {
					'for' : dom['name'],
					'innerHTML' : dom['label']
				});
				spanDom.appendChild(labelDom);
				spanDom.appendChild(dom);
				dom = spanDom;
			}
			/* 绑定事件 */
			if (attributes && attributes['handler']) {
				dom.onclick = attributes['handler'];
			}
			return dom;
		},
		createField : function(queryFields) {
			var dom = null;
			if (queryFields.constructor === Array) {
				dom = this.createDom('div', {
					id : 'query_fields_div'
				});
				for ( var i = 0, fieldsLen = queryFields.length; i < fieldsLen; i++) {
					var item = queryFields[i];
					var field = DomFactory.createDom(item.type, item);
					dom.appendChild(field);
				}
			} else {
				dom = DomFactory.createDom(queryFields.type, queryFields);
			}
			return dom;
		},
		loadSwfUpload:function(){
			/*加载swfupload js文件*/
			var script = this.createDom('script',{src:'http://localhost:8080/cashback/static/js/swfupload.js'});
			document.documentElement.firstChild.appendChild(script);
		},
		initSwfUpload:function(flashURL,uploadURL){
			var settings = {
					flash_url : "http://localhost:8080/cashback/static/swf/swfupload.swf",
					upload_url: "http://localhost:8080/cashback/doSwfUpload",
					post_params: {"JSESSIONID" : ""},
					file_size_limit :"2040MB",
					file_types : "*.*",
					file_types_description : "All Files",
					file_upload_limit : 100,
					file_queue_limit : 0,
					custom_settings : {
						progressTarget : "fsUploadProgress",
						cancelButtonId : "btnCancel"
					},
					debug: false,

					// Button settings
					//button_image_url: "../../image/TestImageNoText_65x29.png",
					button_width: "65",
					button_height: "29",
					button_placeholder_id: "spanButtonPlaceHolder",
					button_text: '<span style="font-size:12">添加附件</span>',
					button_text_style: ".theFont { font-size: 16; }",
					button_text_left_padding: 12,
					button_text_top_padding: 3,
					
					// The event handler functions are defined in handlers.js
					file_queued_handler : fileQueued,
					file_queue_error_handler : fileQueueError,
					file_dialog_complete_handler : fileDialogComplete,
					upload_start_handler : uploadStart,
					upload_progress_handler : questart,//uploadProgress,
					upload_error_handler : uploadError,
					upload_success_handler : swfcomplete,//uploadSuccess,
					upload_complete_handler : uploadComplete,
					queue_complete_handler : queueComplete	// Queue plugin event
					/* // The event handler functions are defined in handlers.js
					file_queued_handler : function(){console.log('fileQueued')},
					file_queue_error_handler : function(){console.log('fileQueueError')},
					file_dialog_complete_handler : function(){console.log('dialog_complete')},
					upload_start_handler : function(){console.log('start')},
					upload_progress_handler : function(){console.log('uploadProgress')},
					upload_error_handler : function(){console.log('uploadError')},
					upload_success_handler : function(){console.log('uploadSuccess')},
					upload_complete_handler : function(){console.log('uploadComplete')},
					queue_complete_handler : function(){console.log('queueComplete')}	// Queue plugin event */
				};
				swfu = new SWFUpload(settings);
		}
	};
	
	/**
	* @class CommonPage
	* @constructor 
	* @param {Object} 配置对象
	* @return CommonPage实例
	*/
	var CommonPage = Class(
			obj,
			{
				northLayoutId : 'north_layout',
				centerLayoutId : 'center_layout',
				centerTableId : 'center_table',
				centerTableBodyId : 'center_table_body',
				queryFieldsFormName : 'query_fields_form',
				saveEditFormName : 'save_edit_form',
				topBarId : 'top_toolbar',
				/* 默认配置 */
				config : {
					/* 模块名称 */
					moduleName : '',
					width : 600,
					height : 500,
					layout : 'border',
					/* 按钮 */
					buttons : [],
					/* 查询字段 */
					queryFields : [],
					/* 表格配置 */
					gridParams : {
						maxHeight : 600,
						idField : 'id',
						columns : [],
						topBar : []
					},
					/* 分页配置 */
					paginationParams : {
						// 默认分页大小
						pageSize : 10
					},
					formParams : {},
					/* 请求配置 */
					requestParams : {
						loadUrlSuffix : '/load.do',
						loadPageUrlSuffix : '/loadPage.do',
						saveUrlSuffix : '/save.do',
						updateUrlSuffix : '/save.do',
						destroyUrlSuffix : 'delete.do'
					}
				},
				/* 默认事件处理 */
				actions : {
					saveFormAction : {
						text : Common.Constant.button_submit,
						iconCls : 'icon-ok',
						handler : function() {
							CommonPage.staticSaveRecord();
						}
					},
					closeFormAction : {
						text : Common.Constant.button_cancal,
						iconCls : 'icon-cancel',
						handler : function() {
							var formId = this.parentNode.parentNode.id;
							$('#' + formId).dialog('close');
						}
					},
					queryAction : {
						type : 'linkbutton',
						id : 'queryLinkButton',
						iconCls:'icon-search',
						handler :function(){
							CommonPage.staticQueryRecord();
						},
						text : '查询'
					}
				},
				getConfig : function() {
					return this.config;
				},
				getBody : function() {
					return document.body;
				},
				initLayout : function() {
					var conf = this.config;
					if (conf.layout == 'border') {
						var mainContainer = document.createElement('div');
						mainContainer.id = this.centerLayoutId;
						mainContainer.className = 'easyui-layout';
						mainContainer.style.width = conf.width;
						mainContainer.style.height = conf.height;

						var northDiv = document.createElement('div');
						northDiv.id = this.northLayoutId;
						northDiv.region = 'north';
						northDiv.style.overflow = 'hidden';

						var centerDiv = document.createElement('div');
						centerDiv.region = 'center';

						var centerTbl = document.createElement('table');
						var centerTblBody = document.createElement('tbody');
						/*var centerTblHead = document.createElement('thead');
						var checkRow = document.createElement('th');
						checkRow.setAttribute('checkbox','true');
						centerTblHead.appendChild(checkRow);*/
						centerTblBody.id = this.centerTableBodyId;
						/*centerTbl.appendChild(centerTblHead);*/
						centerTbl.appendChild(centerTblBody);

						centerTbl.id = this.centerTableId;
						/* centerTbl.style.border = '1px solid'; */
						var toolbarDiv = document.createElement('div');
						toolbarDiv.id = this.topBarId;

						centerDiv.appendChild(toolbarDiv);
						centerDiv.appendChild(centerTbl);

						mainContainer.appendChild(northDiv);
						mainContainer.appendChild(centerDiv);
						// document.body.appendChild(mainContainer);
						document
								.getElementById('container_sitemesh')
								.insertBefore(
										mainContainer,
										document
												.getElementById('footer_sitemesh'));
					}
				},
				initQueryForm : function() {
					var conf = this.config;
					var queryFields = document.getElementById(conf.moduleName
							+ 'query_fields');
					
					 var queryFieldsForm = DomFactory.createDom('form', {
					 name: this.queryFieldsFormName});
					 
					if (!queryFields) {
						queryFields = document.createElement('div');
						queryFields.id = conf.moduleName + 'query_fields';
					}
					if (conf.queryFields) {
						queryFieldsForm.appendChild(DomFactory.createField(conf.queryFields));
						queryFields.appendChild(DomFactory
								.createField(conf.queryFields));
					}
					queryFields.appendChild(queryFieldsForm);
					document.getElementById(this.northLayoutId).appendChild(
							queryFieldsForm);
					this.queryForm = queryFieldsForm;
				},
				initGrid : function() {
					var conf = this.config;
					var loadUrl = CommonPage.requestContext
							+ CommonPage.loadPageUrlSuffix;
					loadUrl = CommonPage
					.genericJsonpUrl(loadUrl);
					if (conf.gridParams) {
						$('#' + this.centerTableId)
								.datagrid(
										{
											url : loadUrl,
											width : 'auto',
											height : 'auto',
											/* 是否显示分页 */
											pagination : true,
											/* 是否显示行号 */
											rownumbers : true,
											checkbox : true,
											method : 'post',
											/*
											 * True
											 * 就会自动扩大或缩小列的尺寸以适应表格的宽度并且防止水平滚动。
											 */
											fitColumns : true,
											/* True 就把行条纹化。（即奇偶行使用不同背景色） */
											striped : true,
											/* 单选 */
											onSelect : proxy(
													function(rowIndex, rowData) {
														var id = $(
																'#'
																		+ this.centerTableId)
																.datagrid(
																		'getSelected');
														if (id != null) {
															var toolbar = document
																	.getElementById(this.topBarId);
															var toolbarBtns = toolbar
																	.getElementsByTagName('a');
															for ( var i = 0; i < toolbarBtns.length; i++) {
																$(
																		'#'
																				+ toolbarBtns[i].id)
																		.linkbutton(
																				{
																					disabled : false
																				});
															}
														}
													}, this),
											onUnselect : proxy(
													function(rowIndex, rowData) {
														var id = $(
																'#'
																		+ this.centerTableId)
																.datagrid(
																		'getSelected');
														if (!id) {
															var toolbar = document
																	.getElementById(this.topBarId);
															var toolbarBtns = toolbar
																	.getElementsByTagName('a');
															for ( var i = 0; i < toolbarBtns.length; i++) {
																var iconCls = toolbarBtns[i].childNodes[0].childNodes[0]
																		.getAttribute('class');
																if (iconCls
																		.indexOf('icon-edit') != -1
																		|| iconCls
																				.indexOf('icon-remove') != -1) {
																	$(
																			'#'
																					+ toolbarBtns[i].id)
																			.linkbutton(
																					{
																						disabled : btnConf['iconCls'] == 'icon-edit'
																								|| btnConf['iconCls'] == 'icon-remove'
																					});
																}

															}
														}
													}, this),
											columns : [ this.config.gridParams['columns'] ],
											toolbar : this.config.gridParams['toolbar'],
											/*frozenColumns : [ [ {
												field : 'id',
												checkbox : true
											} ] ],*/
											onHeaderContextMenu : function(e,
													field) {
												e.preventDefault();
												if (!$('#tmenu').length) {
													createColumnMenu();
												}
												$('#tmenu').menu('show', {
													left : e.pageX,
													top : e.pageY
												});
											}
										});
						/* 自适应gird大小 */
						$(window).resize(proxy(function() {
							$('#center_table').datagrid("resize", {
								height : 'auto',
								width : 'auto'
							});
						}, this));
					}
					/* 初始化gird顶部工具栏 */
					if (conf.gridParams.topBar) {
						var toolbar = document.getElementById(this.topBarId);
						for ( var i = 0; i < conf.gridParams.topBar.length; i++) {
							var btnConf = conf.gridParams.topBar[i];
							var opa = document.createElement('a');
							opa.id = btnConf.urlKey;
							opa.plain = true;
							opa.innerHTML = btnConf.text;
							opa.onclick = btnConf.handler ? btnConf.handler
									: CommonPage
											.getDefaultEvent(btnConf['iconCls']);
							toolbar.appendChild(opa);
							$('#' + btnConf.urlKey)
									.linkbutton(
											{
												iconCls : btnConf['iconCls'],
												plain : 'true',
												disabled : btnConf['iconCls'] == 'icon-edit'
														|| btnConf['iconCls'] == 'icon-remove'
											});
						}
					}
					return $('#center_table');
				},
				initForm : function() {
					/* 初始化form */
					var conf = this.config;
					if (conf.formParams) {
						var formdiv = document.getElementById(conf.moduleName
								+ '_form_div');
						if (!this.formdiv) {
							formdiv = document.createElement('div');
							formdiv.id = conf.moduleName + '_form_div';
							formdiv.style.display = 'none';
							formdiv.style.width = 350;

							var form = DomFactory.createDom('form', {
								name : this.saveEditFormName,
								id : conf.moduleName + '_form',
								'class' : 'form-horizontal',
								className : 'form-horizontal',
								enctype : 'multipart/form-data'
							});
							if (conf.formParams.fields) {
								for ( var i = 0;
										fieldLen = conf.formParams.fields.length,
										i < fieldLen; i++) {
									var formItemDiv = null;
									/** 创建FieldDiv */
									var fieldDiv = DomFactory.createDom('div',
											{
												className : 'form-field'
											});

									/* 创建Field */
									var fieldConf = conf.formParams.fields[i];
									if (fieldConf['type'] == 'checkbox'
											|| fieldConf['type'] == 'radio') {
										formItemDiv = DomFactory
												.createDom(
														'div',
														{
															className : 'form-item form-radio-checkbox-wrap'
														});
									} else {
										formItemDiv = DomFactory.createDom(
												'div', {
													className : 'form-item'
												});
									}
									var field = DomFactory.createDom(
											fieldConf.type, fieldConf);
									fieldDiv.appendChild(field);
									if (fieldConf['type'] == 'file') {
										// var upload =
										// DomFactory.createDom('button',{className:'upload',value:'上传'});
										// fieldDiv.appendChild(upload);
									}
									if (fieldConf['type'] == 'multifile') {
										// var add =
										// DomFactory.createDom('button',{className:'add',value:'+'});
										var remove = DomFactory.createDom(
												'submit', {
													className : 'uploadBtn',
													value : '上传'
												});
										// fieldDiv.appendChild(add);
										fieldDiv.appendChild(remove);
									}
									formItemDiv.appendChild(fieldDiv);
									form.appendChild(formItemDiv);
								}
							}
							formdiv.appendChild(form);
							document.body.appendChild(formdiv);
						}
						return $('#' + conf.moduleName + '_form_div');
					}
				},
				getFormRecord : function() {
					var conf = this.config;
					var form_id = conf.moduleName + 'form';
					var form = document.getElementById(form_id);
					if (form) {
						var els = form.elements;
						for ( var i = 0; i < els.length; i++) {
							alert(els[i].name);
						}
					}
				},
				getDefaultEvent : function(btnIconCls) {
					if (btnIconCls == 'icon-add') {
						return proxy(this.openAddForm, this);
					} else if (btnIconCls == 'icon-edit') {
						return proxy(this.openEditForm, this); // .call(this.centerTable.datagrid('getSelected'));
					} else if (btnIconCls == 'icon-remove') {
						return proxy(this.removeRecord, this);
					}
					else if(btnIconCls == 'icon-search')
					{
						return proxy(CommonPage.staticQueryRecord,this);
					}
				},
				openAddForm : function() {
					/* 初始化新增action */
					var actions = Array();
					var conf = this.config;
					if (conf.formParams.actions) {
						var action = {};
						for ( var i = 0; i < conf.formParams.actions.length; i++) {
							var actionConf = conf.formParams.actions[i];
							action = actionConf;
							actions.push(action);
						}
					}
					var formId = conf.moduleName + '_form_div';
					this.resetForm(this.saveEditFormName);
					$('#' + formId).show();
					var form = document.forms['save_edit_form'];
					form.setAttribute('edit', 'false');
					$('#' + formId).dialog({
						title : '新增' + conf.descriptionName,
						/* 定义是否显示可折叠按钮 */
						collapsible : false,
						/* 定义是否显示最小化按钮 */
						minimizable : false,
						/* 定义是否显示最大化按钮 */
						maximizable : false,
						/*
						 * 定义对话框是否可编辑大小 // resizable:true, // 锁住窗口
						 */
						modal : true,
						/* closeOnEscape 为true的时候，点击键盘ESC键关闭dialog， */
						closeOnEscape : true,
						buttons : actions,
						/* 首次加载分页参数 */
						queryParams : {
							page : 1,
							pageRows : 10
						}
					});
				},
				openEditForm : function(id) {
					var selectId = $('#center_table').datagrid('getSelected');
					if (selectId == null) {
						$.messager
								.alert(Common.Constant.message_warning,
										Common.Constant.message_warning_data,
										'warning');
						return;
					}
					this.openAddForm();
					var form = document.forms['save_edit_form'];
					form.setAttribute('edit', 'true');
					CommonPage.jsonpRequest(CommonPage.requestContext
							+ CommonPage.loadUrlSuffix, 'post', {
						detailId : selectId['id']
					}, proxy(function() {
						this.loadFormData(eval(arguments[0]['data']));
					}, this));
				},
				loadFormData : function() {
					var record = arguments.length == 1 ? arguments[0] : null;
					if (record) {
						var editform = document.forms['save_edit_form'];
						var els = editform.elements;
						var cacheNameId = {};
						for ( var item in record) {
							var val = record[item];
							for ( var i = 0, elsLen = els.length; i < elsLen; i++) {
								var el = els[i];
								var dateCls = el.getAttribute('class');
								if(dateCls && dateCls.indexOf('easyui-datebox')!=-1){
									/*获取date field 原本控件名称*/
									var hidDate = el.nextSibling.children[2];
									var fieldName = hidDate.name;
									if(!cacheNameId.hasOwnProperty(fieldName))
									{
										cacheNameId[fieldName] = el.id;
										cacheNameId.type='date';
									}
								}
								else if(dateCls && dateCls.indexOf('easyui-datetimebox')!=-1)
								{
									/*获取date field 原本控件名称*/
									var hidDate = el.nextSibling.children[2];
									var fieldName = hidDate.name;
									if(!cacheNameId.hasOwnProperty(fieldName))
									{
										cacheNameId[fieldName] = el.id;
										cacheNameId.type = 'datetime';
									}
								}
								if (item == el.name || item == el.id) {
									if (el.nodeName == 'SELECT') {
										var options = el.options;
										var i = 0, optionLen = options.length;
										for (; i < optionLen; i++) {
											if (options[i].value == val) {
												options[i].selected = 'selected';
											}
										}
									} else if (el.type == 'textarea') {
										el.innerHTML = val;
									}
									else {
										el.setAttribute('value', val);
									}
								}
								
							}
						}
						/*设置Date值*/
						for(var p in cacheNameId)
						{
							var dateId = cacheNameId[p];
							var dateVal = record[p];
							var dateType = cacheNameId['type'];
							if(dateVal)
							{
								if(dateType =='date')
								{
									$('#'+dateId).datebox('setValue',dateVal);
								}
								else if(dateType=='datetime')
								{
									$('#'+dateId).datetimebox('setValue',dateVal);
								}
							}
						}
					}
				},
				resetForm : function(formname) {
					var editform = document.forms[formname];
					var els = editform.elements;
					for ( var i = 0; i < els.length; i++) {
						if (els[i].type == 'textarea') {
							els[i].innerHTML = '';
						} else if (els[i].type != 'button'
								&& els[i].type != 'submit') {
							els[i].setAttribute('value', '');
						}
					}
				},
				saveRecord : function() {
					/* var record = this.getFormRecord(); */
				},
				removeRecord : function(id) {
					var selectId = $('#center_table').datagrid('getSelected');
					if (selectId == null) {
						$.messager
								.alert(Common.Constant.message_warning,
										Common.Constant.message_warning_data,
										'warning');
						return;
					} else {
						if(CommonPage.removePreHandler && (typeof CommonPage.removePreHandler)=='function')
						{
							var sure = CommonPage.removePreHandler.call(this,[selectId]);
							if(sure)
							{
								//alert('确定删除');
							}
							else
							{
								//alert('取消删除');
								return;
							}
						}
						CommonPage.jsonpRequest(CommonPage.requestContext
								+ CommonPage.removeUrlSuffix, 'post', {
							id : selectId['id']
						}, function() {
							CommonPage.refreshGrid();
						});
					}
				},
				afterRender : function() {
					/* jquery placeholder */
					/* $('input,textarea').placeholder(); */
				},
				initContext : function() {

				},
				bindDefaultEvent : function() {
					$('.add').live('click', function() {
						var _html = $(this).parents('.form-item').html();
						$(this).parents('.form-item').after(_html);
					});
					$('.uploadBtn1').live('click', function() {
						if ($.browser.msie) {
							console.log('ie submit');
							document.forms['save_edit_form'].submit();
						} else {
							console.log('other submit');
							document.forms['save_edit_form'].submit();
							// $("#uploadForm").submit();
						}
					});
					$('.remove').live('click', function() {
						var index = $(this).parents('.form-item').index();
						alert(index);
						if (index > 0) {
							// $(this).parents('div').parents('div').remove();
						}
					});
				},
				init : function(config) {
					this.config = CommonPage.config;
					for ( var c in config) {
						this.config[c] = config[c];
					}
					this.initLayout();
					this.initQueryForm();
					this.initGrid();
					this.initForm();
					this.afterRender();
					this.bindDefaultEvent();
				}
			});

	/**
	* method jsonp请求url构建函数
	* @constructor 
	* @param {Object} 原始请求url地址
	* @return 构建完成后的jsonp请求url
	*/
	CommonPage.genericJsonpUrl = function(url) {
		if (url.indexOf('?') == -1) {
			url += '?jsoncallback=?';
		} else {
			url += '&jsoncallback=?';
		}
		return url;
	};

	/**
	* method ajax请求方法
	* @constructor 
	* @param {String} 请求地址
	* @param {String} 请求方法
	* @param {Object} 请求数据
	* @param {Function) 回调函数
	* @return null
	*/
	CommonPage.request = function(url, method, data, callback) {
		$.ajax({
			type : method ? method : 'post',
			url : url,
			dataType : 'json',
			data : data,
			success : function(result) {
				callback.call(this, result);
			}
		});
	};
	
	CommonPage.removePreHandle = null;

	/**
	* method ajax jsonp请求方法
	* @constructor 
	* @param {String} 请求地址
	* @param {String} 请求方法
	* @param {Object} 请求数据
	* @param {Function) 回调函数
	* @return null
	*/
	CommonPage.jsonpRequest = function(url, method, data, callback) {
		url = CommonPage.genericJsonpUrl(url);
		CommonPage.request(url, method, data,
				callback);
	};
	
	/* 作用域问题，提供静态查询保存方法，安全范围内可以重载 */
	//保存请求地址
	CommonPage.saveUrlSuffix = '';
	//查询单个对象请求地址
	CommonPage.loadUrlSuffix = '';
	//分页查询请求地址
	CommonPage.loadPageUrlSuffix = '';
	//删除单个对象地址
	CommonPage.removeUrlSuffix = '';
	//请求地址前缀
	CommonPage.requestContext = '';

	/**
	* method 静态条件查询方法
	* @return null
	*/
	CommonPage.staticQueryRecord = function() {
		var form = document.forms['query_fields_form'];
		if (form) {
			var queryType = 'filter';
			/* 过滤型 */
			var queryParam = {};
			var record = {};
			var els = form.elements;
			for ( var i = 0; i < els.length; i++) {
				if (els[i].type != 'select') {
					record[els[i].name] = els[i].value;
					var rule = els[i].rule ? els[i].rule : 'ALLLIKES';
					queryParam[queryType + '_' + rule + '_' + els[i].name] = els[i].value;
				} else if (els[i].type == 'select') {
				}
			}
			/*like this filter_ALLLIKES_JGH="+escape(escape(jgh))+"&filter_ALLLIKES_XM="+escape(escape(xm))+"&filter_EQUALI_YF="+yf+"&filter_EQUALI_NF="+nf */
			CommonPage.queryGrid(queryParam);
		}
	};
	
	/**
	* method 静态保存方法
	* @return null
	*/
	CommonPage.staticSaveRecord = function() {
		/* 验证 */
		var form = document.forms['save_edit_form'];
		var formId = form.getAttribute('id');
		if (!$(formId).form("validate")) {
			return;
		}
		if (form) {
			var record = {};
			var els = form.elements;
			for ( var i = 0, elsLen = els.length; i < elsLen; i++) {
				var el = els[i];
				if (el.type != 'select' && el.type != 'radio'
						&& el.type != 'checkbox') {
					record[els[i].name] = els[i].value;
				}
			}
			var operURL = '';
			var form = document.forms['save_edit_form'];
			if (form.getAttribute('edit') == 'true') {
				operURL = CommonPage.editUrlSuffix;
			} else {
				operURL = CommonPage.saveUrlSuffix;
			}
			CommonPage.jsonpRequest(CommonPage.requestContext + operURL,
					'post', record, function(data) {
						CommonPage.refreshGrid();
					});
		}
	};
	
	/**
	* method 静态刷新方法
	* @return null
	*/
	CommonPage.refreshGrid = function() {
		$('#center_table').datagrid('reload');
	};
	CommonPage.queryGrid = function(params) {
		$('#center_table').datagrid('load', params);
	};
	window.ZDS.CommonPage = CommonPage;
})(window);